<template>
<div class="contest-save">

    <div class="header">
      <el-steps :active="active" finish-status="success">
        <el-step title="比赛设置"></el-step>
        <el-step title="选择题目"></el-step>
        <el-step title="题目设置"></el-step>
      </el-steps>
    </div>
    <div class="step1" v-show="active==1">
        <el-form ref="form" :model="contest" label-width="100px">
            <el-form-item label="比赛名称">
                <el-input v-model="contest.title" require style="width: 350px;"></el-input>
            </el-form-item>
            <el-form-item label="比赛编码">
                <el-input v-model="contest.code" disabled style="width: 350px;"></el-input>
            </el-form-item>
            <el-form-item label="报名时间">
                <el-date-picker
                    v-model="time1"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="比赛开始时间">
                <el-date-picker
                    v-model="time2"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束结束" value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="密码访问">
                <el-radio-group v-model="contest.auth">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
                <el-input  v-if="contest.auth==1" v-model="contest.password" require placeholder="自定义比赛邀请码" required  style="width: 250px;margin-left: 10px;"></el-input>
            </el-form-item>
            <el-form-item label="比赛是否可见">
                <el-radio-group v-model="contest.ishow">
                    <el-radio :label="0">可见</el-radio>
                    <el-radio :label="1">不可见</el-radio>
                </el-radio-group>

            </el-form-item>
            <el-form-item label="开启封榜">
                <el-radio-group v-model="contest.sealRank">
                    <el-radio :label="0">开启</el-radio>
                    <el-radio :label="1">不开启</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="contest.sealRank==0" label="开启封榜的时间">
                <el-date-picker
                    v-model="contest.sealRankTime"
                    type="datetime"
                    placeholder="选择开启封榜的时间" value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
            </el-form-item>
          <!-- 上传图片 -->
          <el-form-item label="缩略图" style="width: 200px;">
            <el-image shape="circle" :src="'/api/user/download/'+contest.avatarId" style="width: 150px; height: 150px" fit="fit" @click="$refs.ImageFile.click()"></el-image>
            <!-- <el-input v-model="inputFile" placeholder="请输入内容" type="file" style="width:230px;"></el-input> -->
            <input type="file" ref="ImageFile" accept="image/*" @change="getImageFile" style="display: none">
            <!--        <span style="margin-left: 10px;color: #bfbfbfbf;">文件ID：{{ formData.fileId }}</span>-->
          </el-form-item>
            <el-form-item label="比赛简介">
                <mavonEditor
                ref="md"
                v-model="contest.description"
                v-bind="$attrs"
                v-on="$listeners"
                @imgAdd="handleImgAdd"
                style="min-height: 600px"/>
            </el-form-item>

        </el-form>
    </div>
    <div class="step2" v-if="active==2">
        <el-card style="width:33.5%;float: right;" v-show="checkList.length>0">
            <div slot="header" style="text-align: left;">
                <span>已经选择的题目</span>
                <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
            </div>
            <div :key="tag.id" v-for="(tag,index) in checkList" style="text-align: left;margin-top: 10px;">
                <el-tag  closable :disable-transitions="false"
                @close="handleClose(tag.id)">
                {{ (index+1)}}:
                <router-link  target="_blank" :to="'/main/problem/detail/'+tag.id" >
                      {{formatCode(tag.code)}} {{ tag.title }}
                </router-link>


                </el-tag>
            </div>

        </el-card>
        <problemList v-on:myValue="returnCheck" :list="checkList" style="width:65%"></problemList>

    </div>
    <div class="step3" v-if="active==3">
        <div v-for="(item,index) in contest.problems" :key="item.problemId">
            <span style="margin-right: 40px;">{{ $MyUtils.numToString(index) }}</span>
            <el-input
            v-model="checkList[index].title"
            :disabled="true" style="width:300px;margin: 10px;">
            </el-input>
            <el-input
            v-model="item.contestTitle" placeholder="改变题目标题"
             style="width:300px;margin: 10px;">
            </el-input>
            <el-input
                v-model="item.rating" placeholder="设置rating分值"
                style="width:125px;margin: 10px;">
            </el-input>
            <el-link style="margin-right: 5px;"  icon="fa el-icon-top fa-lg" :disabled="index==0" @click="upTop(index)"></el-link>
            <el-link icon="fa el-icon-bottom fa-lg" :disabled="index==contest.problems.length-1" @click="upBottom(index)"></el-link>

        </div>
    </div>
    <el-button v-show="active!=1" style="margin-top: 12px;" @click="last">上一步</el-button>
    <el-button v-show="active!=3" style="margin-top: 12px;" @click="next">下一步</el-button>
    <el-button v-show="active==3" type="success" style="margin-top: 12px;" @click="contestSave">保存</el-button>
</div>
</template>

<script lang="ts">
import * as contestApi from '@/api/contest'
import * as problemApi from '@/api/problem'
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import {uploadImage} from '@/api/admin'
import problemList from '@/components/contest/problemList.vue'
// import * as MyUtils from '@/utils/MyUtil'
export default {
name: 'contestSave',
    components:{
        mavonEditor,
        problemList,
    },
    data() {
        return {
            prolbemListShow:true,
            checkList:[],
            active: 1,
            contest:{  // 需要的题目
                auth:0, //默认公开赛，不需要密码
                problems:[],  //题目联系表
                sealRank:1,
                ishow:0,
            },
            time1:[],
            time2:[],
        };
    },

    methods: {
      //获取图片文件
      async getImageFile(event){
        // console.info(event.target.files);
        if(event.target.files[0]&&event.target.files[0].name){
          var imageFile = event.target.files[0];
          // this.problemFileName  = event.target.files[0].name;
          // this.uploadFileFlag = true;
          let form = new FormData();
          form.append('file', imageFile);
          //上传图片
          const res = await uploadImage(form).then(res=>{
            return res.data.data;
          })
          this.contest.avatarId = res;
          this.contest = JSON.parse(JSON.stringify(this.contest))
          // console.info(this.userDetail);
        }
        // if(event.target.files[1])this.outputFile = event.target.files[1].name;
      },
        addTime(){
            this.contest.startTime = this.time2[0];
            this.contest.endTime = this.time2[1];
            this.contest.registerBeginTime = this.time1[0];
            this.contest.registerEndTime = this.time1[1];
        },
        setTime(){
            this.$set( this.time2,0,this.contest.startTime);
            // this.time2[0] = this.contest.startTime;
            this.$set( this.time2,1,this.contest.endTime);
            // this.time2[1] = this.contest.endTime;
            this.$set( this.time1,0,this.contest.registerBeginTime);
            // this.time1[0] = this.contest.registerBeginTime;
            this.$set( this.time1,1,this.contest.registerEndTime);
            // this.time1[1] = this.contest.registerEndTime;
        },

        //保存提交
        contestSave(){
            this.addTime();
            if(this.$MyUtils.isEmpty(this.contest.id)) {  //id为空，表示新增
                contestApi.contestSave(this.contest).then(res=>{
                    if(res.data.success){
                        this.$message({type:"success",message:"添加成功"});
                        this.$router.push('/main/contest');
                    }
                })
            }else{
                contestApi.contestUpdate(this.contest).then(res=>{
                    if(res.data.success){
                        this.$message({type:"success",message:"修改成功"});
                        this.$router.push('/main/contest');
                    }
                })
            }
        },
        last(){
            this.active--;
        },
        next() {
            this.active++;
            if(this.active==3){ //保存题目完毕
                //将题目信息加入到contest中
                for(var i = 0; i<this.checkList.length;i++){
                    var flag = true;
                    for(var j = 0;j<this.contest.problems.length;j++){   //判断是否已存在
                        if(this.contest.problems[j].problemId==this.checkList[i].id){
                            flag = false;
                            break;
                        }
                    }
                    if(flag){   //不存在，加入数组中
                        this.contest.problems.push({"contestTitle":this.checkList[i].title,"problemId":this.checkList[i].id})
                    }

                }
                // console.info(this.contest);
            }
        },
        // 将图片上传到服务器，返回地址替换到md中
      async handleImgAdd(pos, file) {
        let form = new FormData();
        form.append('file', file);

        const res = await uploadImage(form).then(res=>{
            return '/api/user/download/'+res.data.data;
        })
        // console.log(res);
        this.$refs.md.$img2Url(pos, res);
      },
      // 改变选中值时的回调函数
      returnCheck:function(data) {
        // childValue就是子组件传过来的值
        this.checkList = data;
        console.info(data);
      },
      //移除题目
      handleClose(id) {
        // this.prolbemListShow = false;
        // for(var i =0;i<100000;i++);
        // this.checkList.splice(this.checkList.indexOf(tag), 1);
        for(var i = 0;i < this.checkList.length;i++){
          if(this.checkList[i].id == id){
            this.checkList[i] = this.checkList[this.checkList.length-1] //删除最后一个元素，赋值给第 i 个
            this.checkList.pop();
            break;
          }
        }
        // this.prolbemListShow = true;
      },
      formatCode(code){
        return this.$MyUtils.formatCode(code);
      },
      //下移
      upBottom(index){
        this.swap(index,index+1);
      },
      //上移
      upTop(index){
        this.swap(index-1,index);
      },
      //交换contest.problems，checkList的值
      swap(i,j){
        var t = this.contest.problems[i];
        this.contest.problems[i] = this.contest.problems[j]
        this.contest.problems[j] = t;
        t = this.checkList[i];
        this.checkList[i] = this.checkList[j];
        this.checkList[j] = t;
        this.contest.problems = JSON.parse(JSON.stringify(this.contest.problems))
      }
    },
    created(){

        //获取参数，表示修改
        if(this.$route.query.id){
            contestApi.getDetail({"id":this.$route.query.id}).then(async res=>{
                if(res.data.data){


                    if(res.data.data.problems.length){
                        for(var i = 0;i<res.data.data.problems.length;i++){
                            await problemApi.getOneById({"id":res.data.data.problems[i].problemId}).then(res1=>{
                                if(res1.data.data){
                                    this.checkList[i] = res1.data.data;
                                    this.checkList[i].checked = true;
                                }
                            })

                        }
                        // this.checkList = JSON.parse(JSON.stringify(this.checkList))
                    }
                    this.contest = res.data.data;
                    this.setTime();
                }
            })
        }
    },


}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.contest-save .step1{
    padding-top: 10px;
    text-align: left;
    margin-left: 15%;
    width: 70%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    background-color: #ffffff;
}
.contest-save .step3{
    padding-top: 10px;
    text-align: left;
    margin-left: 15%;
    padding-left: 10px;
    width: 70%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    background-color: #ffffff;
}

.contest-save .header{
    margin-left: 10%;
    width: 80%;
    text-align: left;
}
</style>
